<template>
    <div v-show="!isLoading">
        <div class="nav">
            <NAV :navlist="navList" />
        </div>
        <div class="content-wrapper">
            <div class="left-box" v-if="authorInfo && !isMobileLayout">
                <AUTHOR :author="authorInfo" />
            </div>
            <div :class="['text-container', { 'comment-open': !isBlock }]">
                <div class="right-box">
                    <TEXT :text="articleTextInfo" />
                </div>
                
            
                <div class="mobile-comment-container" v-if="isMobileLayout">
                    <div class="interact-mobile">
                        <INTERACT 
                            :user_to_this="userToThisText"
                            @like="handleArticleLike" 
                            @collect="handleArticleCollect"
                            @comment="toggleCommentSection"
                            @reply="handleArticleReply"
                            @block="toggleCommentSection"
                            :isblock="isBlock"
                            :direction="'row'"
                            :key="articleId"
                        />
                    </div>
                    <div class="comment-mobile" v-show="!isBlock">
                        <div class="reply-container" v-show="writeReply">
                            <textarea 
                                v-model="replyContent" 
                                class="styled-textarea" 
                                placeholder="回复..."
                                rows="5"
                            ></textarea>
                            <div class="reply-actions">
                                <button class="cancel-btn" @click="handleArticleReply">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                                <button class="submit-btn" @click="submitReply">
                                    <i class="fas fa-paper-plane"></i> 提交
                                </button>
                            </div>
                        </div>
                        <COMMENT :article_id="articleId" ref="comments" />
                    </div>
                </div>
            </div>
            
     
            <div class="interact-container" v-if="!isMobileLayout">
                <div v-if="user.get_user()" v-show="isBlock" :class="'interact-nav'">
                    <INTERACT 
                        :user_to_this="userToThisText"
                        @like="handleArticleLike" 
                        @collect="handleArticleCollect"
                        @comment="toggleCommentSection"
                        :isblock="isBlock"
                    />
                </div>
                <div :class="['interact-comment', { 'visible': !isBlock }]" v-show="!isBlock">
                    <div class="comment-outer-container">
                        <INTERACT 
                            :user_to_this="userToThisText"
                            @like="handleArticleLike" 
                            @collect="handleArticleCollect"
                            @comment="toggleCommentSection"
                            @reply="handleArticleReply"
                            @block="toggleCommentSection"
                            :isblock="isBlock"
                            :direction="'row'"
                            :key="articleId"
                        />
                        <div class="reply-container" v-show="writeReply">
                            <textarea 
                                v-model="replyContent" 
                                class="styled-textarea" 
                                placeholder="回复..."
                                rows="5"
                            ></textarea>
                            <div class="reply-actions">
                                <button class="cancel-btn" @click="handleArticleReply">
                                    <i class="fas fa-times"></i> 取消
                                </button>
                                <button class="submit-btn" @click="submitReply">
                                    <i class="fas fa-paper-plane"></i> 提交
                                </button>
                            </div>
                        </div>
                        <COMMENT :article_id="articleId" ref="comments" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { inject, onMounted, onUnmounted, ref, watch } from "vue"
import { useRoute } from "vue-router"
import NAV from "./nav.vue"
import TEXT from "./text.vue"
import COMMENT from "./comment/main.vue"
import AUTHOR from "./author_info.vue"
import INTERACT from "./text_interact.vue"
import { get_text_by_id, change_text_like, change_text_collect, change_text_reads, put_text_comments_first } from "@/api/community/main.js"
import { get_user_by_id } from "@/api/user.js"

// 定义状态
let comments = ref(null)
let isLoading = ref(true)
let isBlock = ref(true)
const route = useRoute()
let writeReply = ref(false)
let showText = ref(true)
let communityStore = inject("community")()
let user = inject("user")()
let replyContent = ref('')
let articleId = route.query.id
let articleTextInfo = ref({})
let authorInfo = ref(null)
let userToThisText = ref({ like: 0, collect: 0 })
let isLiking = ref(false)
let isCollecting = ref(false)
let interactwith = ref("20px")
let interactwithMin = ref("0px")
let navList = ref([
    { title: "首页", name: "index" },
    { title: "专栏", name: "community_specialcolumn" },
    { title: "我的", name: "community_delivery" },
    { title: "创作", name: "community_write" },
])

// 响应式布局状态
const isMobileLayout = ref(false)
const checkScreenSize = () => {
    isMobileLayout.value = window.innerWidth < 768
}

// 点赞功能
const handleArticleLike = async () => {
    if (isLiking.value) return
    isLiking.value = true
    articleTextInfo.value.like += userToThisText.value.like ? -1 : 1
    const judge = await change_text_like({
        article_id: articleId,
        author: authorInfo.value.id,
        user: user.value.get_user()?.id,
        type: userToThisText.value.like === 1 ? 0 : 1
    })
    userToThisText.value.like = userToThisText.value.like === 1 ? 0 : 1
    if (!judge) {
        articleTextInfo.value.like -= userToThisText.value.like ? -1 : -1
    }
    isLiking.value = false
}

// 收藏功能
const handleArticleCollect = async () => {
    if (isCollecting.value) return
    isCollecting.value = true
    articleTextInfo.value.collect += userToThisText.value.collect ? -1 : 1
    const judge = await change_text_collect({
        article_id: articleId,
        author: authorInfo.value.id,
        user: user.value.get_user()?.id,
        type: userToThisText.value.collect === 1 ? 0 : 1
    })
    userToThisText.value.collect = userToThisText.value.collect === 1 ? 0 : 1
    if (!judge) {
        articleTextInfo.value.collect -= userToThisText.value.collect ? -1 : 1
    }
    isCollecting.value = false
}

// 切换评论区显示状态
const toggleCommentSection = () => {
    isBlock.value = !isBlock.value
    if (isBlock.value) { 
        interactwith.value = "0px"
        interactwithMin.value = "0px"
    } else {
        interactwith.value = isMobileLayout.value ? "0" : "25vw"
        interactwithMin.value = isMobileLayout.value ? "0" : "350px"
    }
}

// 回复功能
const handleArticleReply = () => {
    writeReply.value = !writeReply.value
}

const submitReply = async () => {
    const data = await put_text_comments_first(articleId, user.value.get_user()?.id, replyContent.value)
    comments.value.addComment(data)
    writeReply.value = false
    replyContent.value = ""
}

// 组件挂载时的逻辑
onMounted(async () => {
    checkScreenSize()
    window.addEventListener('resize', checkScreenSize)
    
    const judgeArticleData = communityStore.value.get_current_reader_article()
    if (judgeArticleData && judgeArticleData.id === route.query.id) {
        articleTextInfo.value = judgeArticleData
        authorInfo.value = articleTextInfo.value.authorinfo
        userToThisText.value = articleTextInfo.value.user_to_text
    } else {
        communityStore.value.set_current_reader_article(null)
        const data = await get_text_by_id(route.query.id, user.value.get_user()?.id)
        if (!data) { 
            showText.value = false
            return
        }
        articleTextInfo.value = {
            text: data["text"],
            title: data["标题"],
            date: data["日期"],
            kind: data["类型"],
            read: data["阅读量"],
            like: data["点赞数"],
            collect: data["收藏数"],
            user_to_text: data["user_to_text"],
            username: data["昵称"],
        }
        authorInfo.value = await get_user_by_id(data["作者ID"])
        articleTextInfo.value.authorinfo = authorInfo.value
        userToThisText.value = articleTextInfo.value.user_to_text
        communityStore.value.set_current_reader_article(articleTextInfo.value)
    }

    if (window.performance) {
        const navigation = window.performance.getEntriesByType("navigation")[0]
        if (navigation?.type === 'navigate') {
            await change_text_reads(route.query.id)
        }
    }

    if (user.value?.get_user()?.id) {
        user.value.initializeBroadcastChannel()
    }
    isLoading.value = false
})

// 组件卸载时的逻辑
onUnmounted(() => { 
    window.removeEventListener('resize', checkScreenSize)
    user.value.cleanupUserStoreListener()
})
</script>

<style scoped>
* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.nav {
    width: 100vw;
    position: sticky;
    top: 0;
    justify-self: center;
    gap: 25px;
    z-index: 1001; 
}

.content-wrapper {
    display: flex;
    width: 100vw;
    height: calc(100vh - 50px);
    overflow: hidden;
}

.left-box {
    width: 20%;
    transition: all 0.3s ease;
}

.text-container {
    width: calc(100vw - 20vw - v-bind(interactwith));
    overflow-y: auto;
    transition: all 0.3s ease;
}
.text-container::-webkit-scrollbar{
    display: none;
}

.interact-container {
    width: v-bind(interactwith);
    min-width: v-bind(interactwithMin);
    padding: 35px;
    right: 0px;
    display: flex;
    flex-direction: column;
    justify-content: left;
    position: relative;
    transition: all 0.3s ease;
}

.interact-nav {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
}

.comment-outer-container {
    display: flex;
    flex-direction: column;
}

.reply-container {
    margin: 20px 0;
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
}

.styled-textarea {
    width: 100%;
    padding: 15px;
    border: none;
    border-bottom: 1px solid #eee;
    font-size: 16px;
    min-height: 100px;
    outline: none;
    background-color: #f9f9f9;
    transition: all 0.3s ease;
    resize: none;
}

.styled-textarea:focus {
    background-color: #fff;
    border-bottom-color: #4285f4;
}

.styled-textarea::placeholder {
    color: #aaa;
    font-style: italic;
}

.reply-actions {
    display: flex;
    justify-content: flex-end;
    padding: 10px 15px;
    background-color: #f5f5f5;
}

.cancel-btn, .submit-btn {
    padding: 8px 16px;
    margin-left: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    display: flex;
    align-items: center;
    transition: all 0.2s ease;
}

.cancel-btn {
    background-color: #f1f1f1;
    color: #666;
}

.cancel-btn:hover {
    background-color: #e0e0e0;
}

.submit-btn {
    background-color: #4285f4;
    color: white;
}

.submit-btn:hover {
    background-color: #3367d6;
}

.submit-btn:disabled {
    background-color: #cccccc;
    cursor: not-allowed;
}

.fas {
    margin-right: 5px;
    font-size: 12px;
}


@media screen and (max-width: 768px) {
    .content-wrapper {
        flex-direction: column;
        height: auto;
        min-height: calc(100vh - 50px);
    }
    
    .left-box {
        display: none;
    }
    
    .text-container {
        width: 100%;
        order: 1;
        height: auto;
        flex-grow: 1;
    }
    
    .interact-container {
        display: none;
    }
    
    .mobile-comment-container {
        width: 100%;
        min-width: 350px;
        order: 2;
        margin-top: 20px;
        padding: 0 15px;
    }
    
    .interact-mobile {
        padding: 15px;
        background: #f5f5f5;
        border-radius: 8px;
        margin-bottom: 15px;
    }
    
    .comment-mobile {
        width: 100%;
    }
}

/* 桌面端隐藏移动版评论区 */
@media screen and (min-width: 769px) {
    .mobile-comment-container {
        display: none;
    }
}
</style>